package com.qf.web.listener;

import com.alibaba.druid.pool.DruidDataSource;
import com.mysql.jdbc.AbandonedConnectionCleanupThread;
import com.qf.util.DataSourceUtil;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * projectName:day15_booksystem_upload
 * author:liuXin
 * time:2021/6/7 10:36
 * description:
 */
@WebListener
public class AppListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {

    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
          //释放资源
          //1.关闭关闭DriverManager中的驱动
          //2关闭线程
        //3.关闭连接池
        System.out.println("webService stop");
        try {
            //1.关闭关闭DriverManager中的驱动
            while(DriverManager.getDrivers().hasMoreElements()){
                DriverManager.deregisterDriver(DriverManager.getDrivers().nextElement());
            }
            System.out.println("jdbc Driver close");
            //2关闭线程(失效连接清理线程)
            AbandonedConnectionCleanupThread.checkedShutdown();
            //3.关闭连接池
            DruidDataSource dataSource=(DruidDataSource) DataSourceUtil.getDataSource();
            dataSource.close();
            System.out.println("clear thread success");
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }
}
